package com.liuxinlong.modules.moc.service.impl;

import com.liuxinlong.common.*;
import com.liuxinlong.common.uploadSMBJ.SMBJConfig;
import com.liuxinlong.common.uploadSMBJ.SMBJInterface;
import com.liuxinlong.enums.EcnBusinessTypeEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.EcnBaseDao;
import com.liuxinlong.modules.dao.RoleRightDao;
import com.liuxinlong.modules.dao.ShareFileDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.entity.EcnBase;
import com.liuxinlong.modules.entity.EcnContent;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.ShareFile;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.moc.dto.EcnDataBom;
import com.liuxinlong.modules.moc.dto.EcnDataMain;
import com.liuxinlong.modules.moc.dto.EcnDataPM;
import com.liuxinlong.modules.moc.service.EcnService;
import com.liuxinlong.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * ecn管理服务层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年1月21日
 */
@Service
@Slf4j
public class EcnServiceImpl implements EcnService {
    @Autowired
    private EcnBaseDao ecnBaseDao;

    @Autowired
    private ShareFileDao shareFileDao;

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private SMBJInterface tt;

    @Autowired
    private SMBJConfig smbjConfig;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleRightDao roleRightDao;

    @Override
    public List<Map<String, Object>> pageEcnList(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<EcnBase> originList = ecnBaseDao.pageEcnList(queryParam);
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        int sort = startNum + 1;
        for (EcnBase item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            map.put("sort", sort);
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    @Override
    public int getEcnCount(Map<String, Object> queryParam) {
        return ecnBaseDao.getEcnCount(queryParam);
    }

    @Override
    public int syncEcnFile() {
        List<ShareFile> hotFileList = tt.connect(smbjConfig.getHotHost());
        List<ShareFile> cepFileList = tt.connectCEP(smbjConfig.getCepHost());
        List<ShareFile> allShareFile = new ArrayList<>();
        allShareFile.addAll(hotFileList);
        allShareFile.addAll(cepFileList);
        Map<String,Map<String,String>> existFileMap = shareFileDao.getAllFileMap(1);
        List<ShareFile> addFileList = new ArrayList<>();
        for (ShareFile shareFile : allShareFile) {
            if (existFileMap.containsKey(shareFile.getSourceNo()+ shareFile.getFileName())) {
                continue;
            }
            shareFile.setId(SnowFlake.nextIdStr());
            addFileList.add(shareFile);
        }
        if (addFileList.isEmpty()) {
            return 0;
        }
        shareFileDao.insertBatch(addFileList);
        return addFileList.size();
    }

    @Override
    public void addEcn(EcnBase ecnBase) {

    }

    @Override
    public ImportResp importEcn(String fileName) {
        String filePath = fileName;
        return excelImportService.excelFile(filePath, 2, new ExcelImportCallBack() {
            @Override
            public Collection<RowError> checkRow(String[] record) {
                return checkRecordValid(record);
            }

            @Override
            public boolean persistRowToDb(String[] record) {
                EcnContent ecnContent = covertToBean(record);
                return false;
//				try {
//					materialReplaceDao.insert(mocDetail);
//					return true;
//				} catch (Exception e) {
//					return false;
//				}
            }

            @Override
            public ImportResp partFailure(ImportResp resp) {
                resp.setRetMessage("导入物料替换数据部分失败，总数=" + resp.getTotal() + ",失败总数=" + resp.getFailedTotal());
                return resp;
            }

            @Override
            public ImportResp allSuccess(ImportResp resp) {
                resp.setRetMessage("导入物料替换数据全部成功，总数=" + resp.getTotal());
                return resp;
            }

            @Override
            public List<Map> convertFailList(List<String[]> failRecords) {
                List<Map> list = new ArrayList<>();
                int sort = 1;
                for (String[] failRecord : failRecords) {
                    Map item = new HashMap();
                    item.put("sort", sort);
                    item.put("targetMaterial", failRecord[1].trim());
                    item.put("replaceMaterial", failRecord[2].trim());
                    item.put("compatibility", StringUtils.equals(failRecord[3].trim(), "是") ? 1 : 2);
                    item.put("ecn", failRecord[4].trim());
                    item.put("regionOne", failRecord[5]);
                    item.put("regionTwo", failRecord[6]);
                    item.put("regionThree", failRecord[7]);
                    list.add(item);
                    sort++;
                }
                return list;
            }

        });
    }

    @Override
    public ImportResp batchAddEcn(List<EcnContent> dataList) {
        return null;
    }

    @Override
    public ImportResp summaryEcn(List<FileManage> fileList) {
        Map<String, Integer> startRowMap = new HashMap<>();
        startRowMap.put("ECN", 99);
        startRowMap.put("1.4.3WPC", 1);
        startRowMap.put("1.4.3产品WPC", 1);
        startRowMap.put("1.4.7WPC", 1);
        startRowMap.put("1.4.3产品WPC", 1);
        startRowMap.put("1.4.3产品WPC", 1);
        Map<Integer, Map<String, List<String[]>>> dataMap = new HashMap<>();
        int i = 1;
        for (FileManage fileInfo : fileList) {
            String filePath = fileInfo.getFilePath();
            Map<String, List<String[]>> fileContentMap;
            try {
                fileContentMap = excelImportService.importExcelMultipleSheet(filePath, startRowMap);
                dataMap.put(i,fileContentMap);
            } catch (Exception e) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "读取文件失败，文件名称：" + fileInfo.getName());
            }
//            if (ObjectUtils.isEmpty(fileContentMap) || ObjectUtils.isEmpty(fileContentMap.get(0)) || ObjectUtils.isEmpty(fileContentMap.get(1)))
//                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "导入失败，文件没有数据");

            // 数据信息解析
            List<String[]> riverContent = fileContentMap.get(0);
            List<Map> riverDataList = new ArrayList<>(riverContent.size());
            log.info("信息数据解析开始");
        }

//        for (int i = 0; i < riverContent.size(); i++) {
//            int sort = i + 1;
//            log.info("第{}行数据解析中", sort);
//            String[] record = riverContent.get(i);
//            log.info("data: {}", Arrays.toString(record));
//            Map<Object, Object> item = new HashMap<>();
//            item.put("sort", sort);
//            item = convertRiverData(record);
//            riverDataList.add(item);
//        }
//        log.info("河道信息数据解析结束，总条数：{}", riverDataList.size());
//        dataMap.put(0, riverDataList);
//        // 截面信息解析
//        List<String[]> sectionContent = fileContentMap.get(1);
//        List<Map> sectionDataList = new ArrayList<>(sectionContent.size());
//        log.info("截面信息数据解析开始");
//        for (int i = 0; i < sectionContent.size(); i++) {
//            int sort = i + 1;
//            log.info("第{}行数据解析中", sort);
//            String[] record = sectionContent.get(i);
//            log.info("data: {}", Arrays.toString(record));
//            Map<Object, Object> item = new HashMap<>();
//            item.put("sort", sort);
//            item = convertData(record);
//            sectionDataList.add(item);
//        }
//        log.info("截面信息数据解析结束，总条数：{}", sectionDataList.size());
//        dataMap.put(1, sectionDataList);
        ImportResp resp = new ImportResp();
//        resp.setFailedList(dataMap);
        return resp;
    }

    @Override
    public void uploadImportTemplateData(Map<String,Object> param) {
        String cuser = String.valueOf(param.get("cuserid")) ;
        String data = String.valueOf(param.get("data"));
        List<String> cuserInfo = Arrays.asList(cuser.split("\\|"));
        List<String> dataInfo = Arrays.asList(data.split("\\|"));
        if (cuserInfo.size()!=4) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR,"111111111111");
        }
        String region = cuserInfo.get(0);
        String userNo = cuserInfo.get(1);
        User operateUser = userDao.getUserBySn(userNo);
        if (ObjectUtils.isEmpty(operateUser)) {
            log.info("上传数据非法，用户：{} 不存在！",userNo);
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR,"用户不存在！");
        }
        String applyTime = cuserInfo.get(2);
        String businessType = cuserInfo.get(3);
        if (StringUtils.equals(businessType, EcnBusinessTypeEnum.MAIN_DATA.getName())) {
            EcnDataMain ecnDataMain = new EcnDataMain();
            ecnDataMain.setMaterialNo(StringUtils.equals(dataInfo.get(0),"-") ? "" : dataInfo.get(0));
            ecnDataMain.setUnit(StringUtils.equals(dataInfo.get(1),"-") ? "" : dataInfo.get(1));
            ecnDataMain.setDescOne(StringUtils.equals(dataInfo.get(2),"-") ? "" : dataInfo.get(2));
            ecnDataMain.setDescTwo(StringUtils.equals(dataInfo.get(3),"-") ? "" : dataInfo.get(3));
            ecnDataMain.setCategory(StringUtils.equals(dataInfo.get(4),"-") ? "" : dataInfo.get(4));
            ecnDataMain.setKeeper(StringUtils.equals(dataInfo.get(5),"-") ? "" : dataInfo.get(5));
            ecnDataMain.setType(StringUtils.equals(dataInfo.get(6),"-") ? "" : dataInfo.get(6));
            ecnDataMain.setMaterialType(StringUtils.equals(dataInfo.get(7),"-") ? "" : dataInfo.get(7));
            ecnDataMain.setStatus(StringUtils.equals(dataInfo.get(8),"-") ? "" : dataInfo.get(8));
            ecnDataMain.setMajorCategories(StringUtils.equals(dataInfo.get(9),"-") ? "" : dataInfo.get(9));
            ecnDataMain.setDraw(StringUtils.equals(dataInfo.get(10),"-") ? "" : dataInfo.get(10));
            ecnDataMain.setVersion(StringUtils.equals(dataInfo.get(11),"-") ? "" : dataInfo.get(11));
            ecnDataMain.setDrawLocation(StringUtils.equals(dataInfo.get(12),"-") ? "" : dataInfo.get(12));
            ecnDataMain.setSize(StringUtils.equals(dataInfo.get(13),"-") ? "" : dataInfo.get(13));
            ecnDataMain.setPriceType(StringUtils.equals(dataInfo.get(14),"-") ? "" : dataInfo.get(14));
            ecnDataMain.setProductModel(StringUtils.equals(dataInfo.get(15),"-") ? "" : dataInfo.get(15));
            ecnDataMain.setDefaultDivision(StringUtils.equals(dataInfo.get(16),"-") ? "" : dataInfo.get(16));
            ecnDataMain.setDivision(StringUtils.equals(dataInfo.get(17),"-") ? "" : dataInfo.get(17));
            ecnDataMain.setModel(StringUtils.equals(dataInfo.get(15),"-") ? "" : dataInfo.get(15));
            ecnDataMain.setProdLine(StringUtils.equals(dataInfo.get(18),"-") ? "" : dataInfo.get(18));
            ecnDataMain.setSeries(StringUtils.equals(dataInfo.get(19),"-") ? "" : dataInfo.get(19));
            ecnDataMain.setInstallFee(StringUtils.equals(dataInfo.get(20),"-") ? "" : dataInfo.get(20));
            ecnDataMain.setPackingSize(StringUtils.equals(dataInfo.get(21),"-") ? "" : dataInfo.get(21));
            ecnDataMain.setCapacity(StringUtils.equals(dataInfo.get(22),"-") ? "" : dataInfo.get(22));
            ecnDataMain.setBarCode(StringUtils.equals(dataInfo.get(23),"-") ? "" : dataInfo.get(23));
            ecnDataMain.setUniversality(StringUtils.equals(dataInfo.get(24),"-") ? "" : dataInfo.get(24));
            ecnDataMain.setClassification(StringUtils.equals(dataInfo.get(25),"-") ? "" : dataInfo.get(25));
            ecnDataMain.setBasicProduct(StringUtils.equals(dataInfo.get(26),"-") ? "" : dataInfo.get(26));
            System.out.println(ecnDataMain);
        } else if (StringUtils.equals(businessType, EcnBusinessTypeEnum.STOCK_DATA.getName())) {

        } else if(StringUtils.equals(businessType, EcnBusinessTypeEnum.PM_DATA.getName())) {
            EcnDataPM ecnDataPM = new EcnDataPM();
            ecnDataPM.setMaterialNo(StringUtils.equals(dataInfo.get(0),"-") ? "" : dataInfo.get(0));
            ecnDataPM.setOrderQTY(StringUtils.equals(dataInfo.get(5),"-") ? "" : dataInfo.get(5));
            ecnDataPM.setBuyer(StringUtils.equals(dataInfo.get(12),"-") ? "" : dataInfo.get(12));
            ecnDataPM.setPM(StringUtils.equals(dataInfo.get(15),"-") ? "" : dataInfo.get(15));
            ecnDataPM.setConfigurationType(StringUtils.equals(dataInfo.get(16),"-") ? "" : dataInfo.get(16));
            ecnDataPM.setVirtualPart(StringUtils.equals(dataInfo.get(25),"-") ? "" : dataInfo.get(25));
            System.out.println(ecnDataPM);
        } else if(StringUtils.equals(businessType, EcnBusinessTypeEnum.BOM_DATA.getName())) {
            EcnDataBom ecnDataBom = new EcnDataBom();
            ecnDataBom.setMaterialNo(StringUtils.equals(dataInfo.get(0),"-") ? "" : dataInfo.get(0));
            ecnDataBom.setSubpart(StringUtils.equals(dataInfo.get(1),"-") ? "" : dataInfo.get(1));
            ecnDataBom.setRef(StringUtils.equals(dataInfo.get(2),"-") ? "" : dataInfo.get(2));
            ecnDataBom.setStartDateOne(StringUtils.equals(dataInfo.get(3),"-") ? "" : dataInfo.get(3));
            ecnDataBom.setQuantity(StringUtils.equals(dataInfo.get(4),"-") ? "" : dataInfo.get(4));
            ecnDataBom.setStructureType(StringUtils.equals(dataInfo.get(5),"-") ? "" : dataInfo.get(5));
            ecnDataBom.setStartDateTwo(StringUtils.equals(dataInfo.get(6),"-") ? "" : dataInfo.get(6));
            ecnDataBom.setEndDate(StringUtils.equals(dataInfo.get(7),"-") ? "" : dataInfo.get(7));
            ecnDataBom.setRemark(StringUtils.equals(dataInfo.get(8),"-") ? "" : dataInfo.get(8));
            ecnDataBom.setSerialNumber(StringUtils.equals(dataInfo.get(12),"-") ? "" : dataInfo.get(12));
            System.out.println(ecnDataBom);
        } else if(StringUtils.equals(businessType, EcnBusinessTypeEnum.ROUTING_DATA.getName())) {

        } else if(StringUtils.equals(businessType, EcnBusinessTypeEnum.SALES_AREA_DATA.getName())) {

        } else {
            log.info("上传数据非法，业务类型不存在！");
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR,"上传数据非法，业务类型不存在！");
        }


    }


    /**
     * 转换数据为入库数据
     *
     * @param record 数据记录
     * @return 入库数据
     */
    private EcnContent covertToBean(String[] record) {
        EcnContent ecnContent = new EcnContent();
//        ecnContent.setTargetMaterial(record[1].trim());
//        ecnContent.setReplaceMaterial(record[2].trim());
//        ecnContent.setCompatibility(StringUtils.equals(record[3].trim(), "是") ? 1 : 2);
//        ecnContent.setEcn(record[4].trim());
//        ecnContent.setRegionOne(record[5].trim());
//        ecnContent.setRegionTwo(record[6].trim());
//        ecnContent.setRegionThree(record[7].trim());
        return ecnContent;

    }

    /**
     * 校验参数合法性
     *
     * @param record 导入数据
     * @return 参数合法性
     */
    private Collection<RowError> checkRecordValid(String[] record) {
        List<RowError> rowErrors = new ArrayList<>();
        if (StringUtils.isEmpty(record[1].trim())) {
            addRowError("被替换物料不能为空", rowErrors);
        } else {
            if (record[1].trim().length() > 500) {
                addRowError("物料号长度不能超过500", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[2].trim())) {
            addRowError("新物料不能为空", rowErrors);
        } else {
            if (record[2].trim().length() > 500) {
                addRowError("新物料号长度不能超过500", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[3].trim())) {
            addRowError("兼容性不能为空", rowErrors);
        } else {
            String com = record[3].trim();
            if (!StringUtils.equals(com, "是") && !StringUtils.equals(com, "否")) {
                addRowError("兼容性字段非法", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[4].trim())) {
            addRowError("ECN号不能为空", rowErrors);
        } else {
            if (record[4].trim().length() > 20) {
                addRowError("ECN号长度不能超过20", rowErrors);
            }
        }

        return rowErrors;
    }

    /**
     * 添加错误行数据
     *
     * @param errorMessage 错误信息
     * @param rowErrors    错误行数据
     */
    private void addRowError(String errorMessage, List<RowError> rowErrors) {
        RowError rowError = new RowError(errorMessage);
        rowErrors.add(rowError);
    }

    /**
     * 校验参数合法性
     *
     * @param record 汇总数据
     * @return 参数合法性
     */
    private Collection<RowError> checkSummaryRecordValid(String[] record) {
        List<RowError> rowErrors = new ArrayList<>();
        if (StringUtils.isEmpty(record[1].trim())) {
            addRowError("被替换物料不能为空", rowErrors);
        } else {
            if (record[1].trim().length() > 500) {
                addRowError("物料号长度不能超过500", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[2].trim())) {
            addRowError("新物料不能为空", rowErrors);
        } else {
            if (record[2].trim().length() > 500) {
                addRowError("新物料号长度不能超过500", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[3].trim())) {
            addRowError("兼容性不能为空", rowErrors);
        } else {
            String com = record[3].trim();
            if (!StringUtils.equals(com, "是") && !StringUtils.equals(com, "否")) {
                addRowError("兼容性字段非法", rowErrors);
            }
        }
        if (StringUtils.isEmpty(record[4].trim())) {
            addRowError("ECN号不能为空", rowErrors);
        } else {
            if (record[4].trim().length() > 20) {
                addRowError("ECN号长度不能超过20", rowErrors);
            }
        }

        return rowErrors;
    }

}
